package cn.itcast.bos.web.action.base;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.domain.base.SubArea;
import cn.itcast.bos.service.base.SubAreaService;
import cn.itcast.bos.web.action.common.BaseAction;

@SuppressWarnings("serial")
@Namespace("/")
@ParentPackage("json-default")
@Controller
@Scope("prototype")
public class SubAreaAction extends BaseAction<SubArea>{
	
	@Autowired
	private SubAreaService subAreaService;
	
	private File file;
	
	public void setFile(File file) {
		this.file = file;
	}

	@Action(value="importSubArea",results={@Result(name="success",location="pages/base/sub_area.html")})
	public String importSubArea() throws Exception{
		//list集合用于添加subarea对象
		List<SubArea> list = new ArrayList<>();
		//创建解析excel解析对象hssfworkbook
		HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(file));
		HSSFSheet sheet = workbook.getSheetAt(0);
		for(Row rows : sheet){
			//跳过第一行
			if(rows.getRowNum() == 0){
				continue;
			}
			//跳过空行
			if(rows.getCell(0) == null || StringUtils.isBlank(rows.getCell(0).getStringCellValue())){
				continue;
			}
			SubArea a = new SubArea();
			String id = RandomStringUtils.randomNumeric(4);
			a.setId(id);
			a.setAssistKeyWords(rows.getCell(8).getStringCellValue());
			a.setEndNum(rows.getCell(6).getStringCellValue());
			a.setKeyWords(rows.getCell(4).getStringCellValue());
			a.setStartNum(rows.getCell(5).getStringCellValue());
			a.setSingle(rows.getCell(7).getStringCellValue().charAt(0));
			list.add(a);
		}
		subAreaService.save(list);
		return SUCCESS;
	}

}
